package ray.create;

import org.mybatis.generator.api.GeneratedXmlFile;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.xml.Document;
import org.mybatis.generator.api.dom.xml.TextElement;
import org.mybatis.generator.api.dom.xml.XmlElement;
import org.mybatis.generator.codegen.XmlConstants;

import java.util.ArrayList;
import java.util.List;

/**
 * generate service class
 *
 * @author ray
 * @date 2016-03-17 10:34:45
 */
public class DubboServicePlugin extends PluginAdapter {

    private String pojoUrl;
    private String servicePack;
    private String targetProject;

    @Override
    public boolean validate(List<String> arg0) {
        this.servicePack = properties.getProperty("servicePackage");
        this.pojoUrl = context.getJavaModelGeneratorConfiguration().getTargetPackage();
        this.targetProject = properties.getProperty("targetProject");
        return true;
    }

    @Override
    public List<GeneratedXmlFile> contextGenerateAdditionalXmlFiles(IntrospectedTable introspectedTable) {
        List<GeneratedXmlFile> files = new ArrayList<GeneratedXmlFile>();
        String table = introspectedTable.getBaseRecordType();
        String tableName = table.replaceAll(this.pojoUrl + ".", "");
        Document documentService = new Document(
                XmlConstants.MYBATIS3_MAPPER_CONFIG_PUBLIC_ID,
                XmlConstants.MYBATIS3_MAPPER_CONFIG_SYSTEM_ID);
        XmlElement dubboService = new XmlElement("dubbo");
        documentService.setRootElement(dubboService);
        dubboService.addElement(new TextElement(("<dubbo:service interface=\"" + servicePack + "." + tableName + "Service\" ref=\"" + Utils.toLowerCase(tableName) + "Service\" timeout=\"500000\" />")));
        GeneratedXmlFile fileService = new GeneratedXmlFile(documentService, "dubboService.xml", "com.dubbo", targetProject, true, context.getXmlFormatter());
        files.add(fileService);

        Document documentReference = new Document(
                XmlConstants.MYBATIS3_MAPPER_CONFIG_PUBLIC_ID,
                XmlConstants.MYBATIS3_MAPPER_CONFIG_SYSTEM_ID);
        XmlElement dubboReference = new XmlElement("dubbo");
        documentReference.setRootElement(dubboReference);
        dubboReference.addElement(new TextElement(("<dubbo:reference interface=\"" + servicePack + "." + tableName + "Service\" id=\"" + Utils.toLowerCase(tableName) + "Service\"  timeout=\"50000\" />")));
        GeneratedXmlFile fileReference = new GeneratedXmlFile(documentReference, "dubboReference.xml", "com.dubbo", targetProject, true, context.getXmlFormatter());
        files.add(fileReference);
        return files;
    }

}
